var db=require('../utils/db.js');
var md5=require('../utils/md5.js');
var formidable = require('formidable');
var sd=require('silly-datetime');
var fs=require('fs');
var gm = require('gm');

exports.showIndex=function (req,res) {
    console.log('index.name:'+req.session.name);
    var ava=req.session.name+'/'+req.session.avatar || 'default/avatar.jpg';
    console.log('index.avatar:'+ava);
    res.render('index',{
        "name": req.session.name,
        "avatar": ava,
        "active": 'index',
    });
};

exports.showRegister=function (req,res) {
    res.render('register',{
        "name": req.session.name,
        "active":'register'
    });
};

exports.doRegister=function (req,res) {
    let name=req.param('name');
    let password=req.param('password');
    password=md5(password);
    db.find('users',{
        'name':name
    },function (err,result) {
        if(err){
            res.send('-3');
            return;
        }
        if(result.length !== 0){
            res.send('-1');
            return;
        }
        db.insertOne('users',{
            'name':name,
            'password':password
        },function (err,result) {
            if(err){
                console.log('-3333');
                res.send('-3');
                return;
            }
            req.session.login=true;
            req.session.name=name;
            res.send('1');
        });
    });
};

exports.showLogin=function (req,res) {
    res.render('login',{
        "name":req.session.name,
        "active":'login'
    });
};

exports.doLogin=function (req,res) {
    let name=req.param('name');
    let password=req.param('password');
    password=md5(password);
    console.log('loginname:'+name);
    db.find('users',{
        'name':name
    },function (err,result) {
        console.log('res:'+result);
        if(result && result.length === 1 && result[0].password === password){
            req.session.login=true;
            req.session.name=name;
            req.session.avatar=result[0].avatar;
            res.send('1');
            return;
        }
        console.log('登录失败了:');
        res.send('-1');
    });
};

exports.goAvatar=function (req,res) {
    res.render('avatar',{
        "name":req.session.name,
        "active":'avatar'
    });
};

exports.setAvatar=function (req,res) {
    console.log('设置头像post');
    var form = new formidable.IncomingForm();
    var tempPath=__dirname+'/../avatar/temp/';
    form.uploadDir = tempPath;
    form.parse(req, function(err, fields, files) {
        console.log(fields);
        console.log(files);
        if(files.avatar.size > 1024 *100){
            fs.unlink(files.avatar.path, (err) => {
                if (err) {throw err;}
                console.log('临时文件已删除');
            });
            console.log('请上传1M 内图片');
            res.send('-1');
            return;
        }

        var oldPath=files.avatar.path;
        var extname=req.session.avatar+files.avatar.name;
        if(extname.length > 10){
            extname=extname.substr(extname.length-10);
        }
        req.session.avatar=extname;//设置用户头像名
        var file=__dirname+'/../avatar/'+req.session.name;
        fs.exists(file, function(exists) {
            if(!exists){
                fs.mkdir(file,function (err) {
                    if(err){
                      throw err;
                    }
                    var newPath=__dirname+'/../avatar/'+req.session.name+'/'+extname;
                    console.log('newPath:'+newPath);
                    fs.rename(oldPath, newPath, function (err) {
                        delFile(files.avatar.path);
                        if(err){
                            console.log(err);
                            res.send('-1');
                            return;
                        }
                        res.redirect('/cut');
                    })
                });
            }else{
                var newPath=__dirname+'/../avatar/'+req.session.name+'/'+extname;
                fs.rename(oldPath, newPath, function (err) {
                    delFile(files.avatar.path);
                    if(err){
                        console.log(err);
                        res.send('-1');
                        return;
                    }
                    res.redirect('/cut');
                })
            }
        });
        //更新数据库头像信息
        db.update('users',{'name':req.session.name},{'avatar':extname},function (err,result) {
            if(err){
                throw err;
            }
            console.log('用户头像更新成功！');
        })
    });
};

exports.cut=function (req,res) {
    res.render('cut',{
        "name":req.session.name,
        "avatar":req.session.avatar || 'avatar.jpg',
        "active":'avatar'
    });
};

exports.docut=function (req,res) {
    console.log('param..w.'+req.param('w'));
    console.log('param..h.'+req.param('h'));
    console.log('param..x.'+req.param('x'));
    console.log('param..y.'+req.param('y'));

    var w= req.param('w');
    var h=req.param('h');
    var x= req.param('x');
    var y= req.param('y');
    // var avatar=__dirname+'/../uploads/三九/2.jpg';
    var avatar=__dirname+'/../avatar/'+req.session.name+'/'+req.session.avatar;
    gm(avatar).crop(w,h,x,y)
        // .resize(100,100,'!')
        .write(avatar, function (err) {
            if (err){
                throw err;
            }
            res.send('1');
        });



};


function delFile(file) {
    fs.exists(file, function(exists) {
        if(exists){
            fs.unlink(file, (err) => {
                if (err) throw err;
                console.log('临时文件已删除');
            });
        }
    });
}